// uni_modules/rsa-native/ios/RSAEncrypt.swift

import Foundation
import Security

@objc public class RSAEncrypt: NSObject {
    @objc public static func encryptWithPublicKey(_ text: String) -> String {
        let publicKeyPEM = """
        -----BEGIN PUBLIC KEY-----
        MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH
        nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==
        -----END PUBLIC KEY-----
        """

        guard let keyData = stripPublicKeyHeader(pem: publicKeyPEM),
              let keyRef = SecKeyCreateWithData(keyData as CFData,
                                                 [kSecAttrKeyType: kSecAttrKeyTypeRSA,
                                                  kSecAttrKeyClass: kSecAttrKeyClassPublic] as CFDictionary,
                                                 nil) else {
            return "error: invalid key"
        }

        let plainData = text.data(using: .utf8)!
        var error: Unmanaged<CFError>?
        guard let encryptedData = SecKeyCreateEncryptedData(keyRef, .rsaEncryptionPKCS1, plainData as CFData, &error) else {
            return "error: \(error!.takeRetainedValue().localizedDescription)"
        }

        return (encryptedData as Data).base64EncodedString()
    }

    private static func stripPublicKeyHeader(pem: String) -> Data? {
        let lines = pem.components(separatedBy: "\n").filter {
            !$0.contains("BEGIN") && !$0.contains("END") && !$0.trimmingCharacters(in: .whitespaces).isEmpty
        }
        let base64String = lines.joined()
        return Data(base64Encoded: base64String)
    }
}